using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using PSLibrary = Microsoft.Office.Project.Server.Library;

namespace RBSViewer
{
    public partial class MainForm : Form
    {
        private const string LOOKUPTABLESWEBSERVICE = "_vti_bin/PSI/LookupTable.asmx";
        private const string RESOURCESWEBSERVICE = "_vti_bin/PSI/Resource.asmx";
        RBSViewer.LookupTablesWsc.LookupTable LookupTable = new RBSViewer.LookupTablesWsc.LookupTable();
        RBSViewer.ResourceWsc.Resource Resource = new RBSViewer.ResourceWsc.Resource();
        public static string PWAURL;
        public string RdbServer;
        public string RdbDatabase;
        Guid noRBSGuid = new Guid(Guid.NewGuid().ToString());
        DataSet ResourceDS = new DataSet();
        TreeNode currentNode;
        BulkEdit bulkeditwindow = new BulkEdit();
        TreeNode userInvoke = null;

        public MainForm()
        {
            InitializeComponent();
        }

        public void BindForm()
        {
            //Binf the form to the RDB resource data
            LookupTable.Url = PWAURL + LOOKUPTABLESWEBSERVICE;
            LookupTable.Credentials = CredentialCache.DefaultCredentials;
            Resource.Url = PWAURL + RESOURCESWEBSERVICE;
            Resource.Credentials = CredentialCache.DefaultCredentials;
            dataGridView1.AllowUserToAddRows = false;
            try
            {
                Guid[] lutlist = new Guid[] { PSLibrary.LookupTables.RBS_LT_UID };

                //Retrieve the possible RBS Lookup Table values
                //Use these values to build up the treeNodes for the treeview
                RBSViewer.LookupTablesWsc.LookupTableDataSet myds = LookupTable.ReadLookupTablesByUids(lutlist, false, 1033);
                if (myds.LookupTableTrees.Count > 0)
                {
                    foreach (RBSViewer.LookupTablesWsc.LookupTableDataSet.LookupTableTreesRow row in myds.LookupTableTrees)
                    {
                        if (row["LT_PARENT_STRUCT_UID"] == DBNull.Value)
                        {
                            //This'll be the root node then
                            TreeNode tn = treeView1.Nodes.Add(row.LT_UID.ToString(),row.LT_VALUE_TEXT.ToString());
                            tn.Tag = row.LT_STRUCT_UID.ToString();
                        }
                        else
                        {                  
                            TreeNode mytreenode = DoRecursion(treeView1.Nodes, row.LT_PARENT_STRUCT_UID);
                            TreeNode tn = mytreenode.Nodes.Add(row.LT_UID.ToString(), row.LT_VALUE_TEXT);
                            tn.Tag = row.LT_STRUCT_UID.ToString();
                        }
                    }

                }
                //Always add a 'No RBS Value' Node
                TreeNode t = treeView1.Nodes.Add(noRBSGuid.ToString(), "No RBS Value");
                t.Tag = noRBSGuid.ToString();

                treeView1.ExpandAll();

                
                LoginForm.statusform.statusstring = "Connecting to Reporting Database";
                String connectionstring;
                String commandstring = "";

                //Now connect to the RDB and pull back all the resources
                connectionstring = "Integrated Security=true;database=" + RdbDatabase + ";server=" + RdbServer + ";";
                commandstring += "select ResUserView.ResourceUID, ResUserView.ResourceName, ";
	            commandstring += "ResUserView.ResourceEmailAddress, ResUserView.RBS, ";
	            commandstring += "LT.MemberUID as RBSUID ";
                commandstring += "from MSP_EpmResource_UserView ResUserView INNER JOIN MSP_EpmLookupTable LT ON ";
                commandstring += "ResUserView.RBS = CAST(LT.MemberFullValue AS nvarchar(255)) AND ResUserView.ResourceType ='2' ";
                commandstring += "AND LT.LookupTableUID = '00008E67-65A3-4898-BAAA-D82D995BBB02'";

                SqlConnection myconn = new SqlConnection(connectionstring);
                SqlDataAdapter myadp = new SqlDataAdapter(commandstring, myconn);
                LoginForm.statusform.statusstring = "Downloading Resource Information";
                ResourceDS.Clear();
                myadp.Fill(ResourceDS); 
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                Application.Exit();
            }
            //Now we have the data add the resources to the relevant RBS node
            setResources(treeView1.Nodes[0]);

            if (treeView1.Nodes[0].Parent == null)
            {
                treeView1.SelectedNode = treeView1.Nodes[0];
            }
        }

        private TreeNode DoRecursion(TreeNodeCollection treenodecoll, Guid parentguid)
        {
            foreach (TreeNode node in treenodecoll)
            {
                if (node.Tag.ToString() == parentguid.ToString())
                {
                    return node;
                }
                else
                {
                    TreeNode tn = DoRecursion(node.Nodes, parentguid);
                    if (tn != null)
                        return tn;
                }
            }
            return null;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //Persist all the values
            Properties.Settings.Default.PWAURL = PWAURL;
            //Not sure why but RdbServer doesn't seem to want to persist...
            Properties.Settings.Default.RDBServer = RdbServer;
            Properties.Settings.Default.RDBDatabase = RdbDatabase;
            Properties.Settings.Default.Save();
            Properties.Settings.Default.Upgrade();
            Properties.Settings.Default.Save();
        }

        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            //When the user clicks on a node then set that node to be active and add the relevant resources to the list
            TreeNode tn = treeView1.GetNodeAt(e.X, e.Y);
            setResources(tn);
        }

        //Set the correct Resources to this TreeNode
        private void setResources(TreeNode tn)
        {
            if (tn != null)
            {
                currentNode = tn;
                Guid RBSGuid = new Guid(currentNode.Tag.ToString());
                AddResourcesToList(RBSGuid);
                RBSNodeLabel.Text = tn.Text;
            }
        }
/*
        //After the user has checked an RBS node
        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            //If checking parent node then check all sub-nodes too
            if (e.Action == TreeViewAction.ByMouse)
                userInvoke = e.Node;

            if (IsDescendent(userInvoke, e.Node))
            {
                foreach (TreeNode tn in e.Node.Nodes)
                    tn.Checked = e.Node.Checked;
            }

            if (IsDescendent(e.Node, userInvoke))
            {
                TreeNode pn = e.Node.Parent;
                if (pn == null)
                    return;

                bool bAllChecked = true;
                foreach (TreeNode tn in pn.Nodes)
                    bAllChecked = bAllChecked && tn.Checked;

                if (pn.Checked && !bAllChecked)
                    pn.Checked = false;

                if (!pn.Checked && bAllChecked)
                    pn.Checked = true;
            }
        }
       
        bool IsDescendent(TreeNode parent, TreeNode desc)
        {
            return desc.FullPath.IndexOf(parent.FullPath) == 0;
        }
        */
        private void viewResourcesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (currentNode != null)
            {
                Guid RBSGuid = new Guid(currentNode.Tag.ToString());
                AddResourcesToList(RBSGuid);
            }
        }

        private void AddResourcesToList(Guid RBSGuid)
        {

            String st;
            if (RBSGuid == noRBSGuid)
                st = "RBSUID IS NULL";
            else
                st = "RBSUID = '" + RBSGuid.ToString() + "'";

            ResourceDS.Tables[0].DefaultView.RowFilter = st;
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = ResourceDS.Tables[0].DefaultView;
            ResCountLabel.Text = ResourceDS.Tables[0].DefaultView.Count.ToString();
        }

        //The user has selected that they want to do a bulk edit 
        // for all resources checked in the current view
        private void button1_Click(object sender, EventArgs e)
        {
            String[] strarr = new String[dataGridView1.Rows.Count];
            Guid[] Guidarr = new Guid[dataGridView1.Rows.Count];
            int counter = 0;
            //Need to pull back all resources that are checked
            for(int i=0;i<dataGridView1.Rows.Count; i++)
            {
                if ((bool)dataGridView1.Rows[i].Cells[0].FormattedValue)
                {
                    //Row is checked
                    Guidarr[counter] = new Guid(dataGridView1.Rows[i].Cells[1].Value.ToString());
                    strarr[counter] = dataGridView1.Rows[i].Cells[2].Value.ToString();
                    counter++;
                }
            }

            if (counter > 0)
            {
                Guid[] tempGuidarr = new Guid[counter];
                for (int j = 0; j < counter; j++)
                {
                    tempGuidarr[j] = Guidarr[j];
                }
                bulkeditwindow.BindData(true, tempGuidarr, strarr, counter, RdbDatabase,RdbServer);
                bulkeditwindow.ShowDialog();
            }
            else
            {
                MessageBox.Show("No Resources selected");
            }
        }

        //The user has selected that they want to do a bulk edit 
        // for all resources under the selected RDS Nodes
        private void button2_Click(object sender, EventArgs e)
        {
            //Need to pull back all RBS nodes that are checked
            int nodecounter = 0;

            foreach (TreeNode TN in treeView1.Nodes)
            {
                nodecounter+= GetTreeViewCount(TN);
                //Need to add root nodes
                nodecounter++;
            }
            String[] strarr = new String[nodecounter];
            Guid[] Guidarr = new Guid[nodecounter];

            //Need to pull back all RBS nodes that are checked
            int counter = 0;

            foreach (TreeNode TN in treeView1.Nodes)
            {
                counter += GetTreeViewChecked(TN, strarr, Guidarr,0);
            }
            if (counter > 0)
            {
                bulkeditwindow.BindData(false, Guidarr, strarr, counter,RdbDatabase,RdbServer);
                bulkeditwindow.ShowDialog();
            }
            else
            {
                MessageBox.Show("No RBS nodes selected");
            }
        }

        private int GetTreeViewChecked(TreeNode TN, String[] strarr, Guid[] Guidarr, int counter)
        {
            if (TN.Checked)
            {
                strarr[counter] = TN.Text;
                Guidarr[counter] = new Guid(TN.Tag.ToString());
                counter++;
            }
            foreach (TreeNode TRN in TN.Nodes)
            {
                counter = GetTreeViewChecked(TRN, strarr, Guidarr,counter);
            }
            return counter;
        }

        private int GetTreeViewCount(TreeNode TN)
        {
            int retval = 0;
            retval += TN.Nodes.Count;
            foreach (TreeNode trn in TN.Nodes)
            {
                retval += GetTreeViewCount(trn);
            }
            return retval;
        }

        //This is the refresh button
        private void button3_Click(object sender, EventArgs e)
        {
            //Rebind the data to the treeview and grid
            treeView1.Nodes.Clear();
            dataGridView1.DataSource = null;
            BindForm();
        }
    }
}